package com.jzwl.common.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

import com.jzwl.common.security.dao.UserDao;
import com.jzwl.common.security.pojo.UserBean;
/**

 * 自定义用户验证服务 
 *
 */
public class CustomUserDetailsService implements UserDetailsService {
	
	@Autowired
	private UserDao userDao;//业务DAO
	
	/**
	 * 根据用户名获取用户-权限等用户信息
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		UserDetails user = null;
		try {
			List<UserBean> dbUserlist = userDao.getUser(username);
			user = new User(dbUserlist.get(0).getUsername(), dbUserlist.get(0).getPassword().toLowerCase(), true, true, true, true, getAuthorities(dbUserlist));
		} catch (Exception e) {
			throw new UsernameNotFoundException("Error in retrieving user");
		}
		return user;
	}

	/**
	 * 获得访问角色权限
	 * @param access
	 * @return
	 */
	private Collection<GrantedAuthority> getAuthorities(List<UserBean> dbUserlist) {
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
		// 所有的用户默认拥有ROLE_USER权限
		for(int i = 0; i < dbUserlist.size(); i++){
			List<Map<String,Object>> list = userDao.findPrivilege(String.valueOf(dbUserlist.get(i).getRoleId()));
			if (list != null && list.size() > 0) {
				for (Map<String,Object> privilegeMap : list) {
					authList.add(new GrantedAuthorityImpl(String.valueOf(privilegeMap.get("id"))));
				}
			}
		}
		return authList;
	}

}
